package com.supplychainapi.utils;


import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class RandomUtils {

	/**
	 * 主函数，作为调用和测试生成验证码方法的入口
	 */
	public static void main(String[] args) {
//		for (int i = 0; i < 1000; i++) {
//			System.out.println("【" + i + "】" + "      【the verification code is】       " + createVerificationCode(6));
//		}
		Map<String, String> params = new HashMap<String, String>();
		params.put("pay_sourceid", "102");
		params.put("pay_order", "S20170816000001");
		String sign = "";
		Collection<String> keyset = params.keySet();
		List<String> list = new ArrayList<String>(keyset);
		Collections.sort(list);
		for (int i = 0; i < list.size(); i++) {
			sign = sign + list.get(i) + "=" + params.get(list.get(i)) + "&";
		}
		String mdKey = "13d2b57591d5f87992fce423b9503a14";
		String tmpSign1 = MD5Utils.MD5Encode(sign + mdKey);
		String tmpSign2 = tmpSign1.substring(0, tmpSign1.length() - 1) + "w";
		String finalSign = MD5Utils.MD5Encode(tmpSign2);
		params.put("sign", finalSign);
		System.out.println(params);
	}

	/**
	 * 生成指定长度的验证码
	 */
	public static final String createVerificationCode(int verificationCodeLength) {
		// 所有候选组成验证码的字符，可以用中文
		String[] verificationCodeArrary = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
		String verificationCode = "";
		Random random = new Random();
		// 此处是生成验证码的核心了，利用一定范围内的随机数做为验证码数组的下标，循环组成我们需要长度的验证码，做为页面输入验证、邮件、短信验证码验证都行
		for (int i = 0; i < verificationCodeLength; i++) {
			verificationCode += verificationCodeArrary[random.nextInt(verificationCodeArrary.length)];
		}
		return verificationCode;
	}
	
	public static String buildKey(String cacheName, Object key) {
		if (key instanceof Number)
			return String.format("%s:I:%s", cacheName, key);
		else {
			Class keyClass = key.getClass();
			if (String.class.equals(keyClass) || StringBuffer.class.equals(keyClass) || StringBuilder.class.equals(keyClass)) {
				return String.format("%s:SHOPID:%s", cacheName, key);
			}
		}
		return String.format("%s:O:%s", cacheName, key);
	}
}
